package com.yz.sharkim.websocket;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yz.sharkim.annotation.Id;
import com.yz.sharkim.annotation.IdMapping;
import com.yz.sharkim.annotation.WebSocketController;
import com.yz.sharkim.entity.User;
import com.yz.sharkim.entity.enums.CommonResult;
import com.yz.sharkim.entity.message.BaseMessage;
import com.yz.sharkim.entity.message.request.AddFriend;
import com.yz.sharkim.entity.message.request.Authentication;
import com.yz.sharkim.entity.message.request.UserList;
import com.yz.sharkim.entity.message.response.AuthenticationResponse;
import com.yz.sharkim.entity.message.response.CommonResponse;
import com.yz.sharkim.entity.message.response.UserListResponse;
import com.yz.sharkim.service.IUserService;
import com.yz.sharkim.util.AESUtils;
import io.netty.channel.Channel;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;

/**
 * @author yangzheng
 * @version 1.0
 * @date 2019/11/4
 */
@WebSocketController
public class UserController {
    /**
     * Token过期时间24小时
     */
    private long EXPIRE_TIME = 24 * 60;

    private final String TOKEN_SPLIT = "~";

    @Autowired
    private IUserService userService;

    @IdMapping(BaseMessage.AUTHENTICATION)
    public BaseMessage login(Authentication message, Channel channel) {
        User user = null;
        if (message.getToken() != null) {
            val token = AESUtils.defaultDecrypt(message.getToken()).split(TOKEN_SPLIT);
            if (token.length != 2) {
                return CommonResponse.field("异常鉴权");
            }
            if (LocalDateTime.parse(token[1]).isAfter(LocalDateTime.now())) {
                user = userService.getById(Integer.valueOf(token[0]));
            } else {
                return CommonResponse.field("鉴权码过期,请重新登陆");
            }
        } else {
            user = userService.getOne(new QueryWrapper<User>().eq(User.USERNAME, message.getUsername()));
            if (user == null || !user.getPassword().equals(AESUtils.defaultEncrypt(message.getPassword()))) {
                return CommonResponse.field("账号或密码错误");
            }
        }
        if (user == null) {
            return CommonResponse.field("");
        } else {
            user.setPassword(null);
            userService.online(channel, user);
            val token = AESUtils.defaultEncrypt(user.getId() + TOKEN_SPLIT + LocalDateTime.now().plusMinutes(EXPIRE_TIME));
            return new AuthenticationResponse().setUser(user).setToken(token);
        }
    }

    @IdMapping(BaseMessage.GET_USER_LIST)
    public BaseMessage userList(UserList message, User current) {
        val list = userService.getUserList();
        list.remove(current);
        return new UserListResponse().setUsers(list);
    }

    @IdMapping(BaseMessage.ADD_FRIEND)
    public BaseMessage addFriend(AddFriend addFriend, User current) {
        return CommonResponse.success("已发送申请");
    }

}
